import {
	getLocationQQ
} from '@/utils/api.js';

export const publics = {
	data() {
		return {
			userInfo: {},
			viewInfo: {},
			pageHeight: 0,
			pageHeighthaveBar: 0,
			pageHaveBarStyle: {},
			pageNoHaveBarStyle: {},
			KeyboardHeight: 0, // 获取键盘高度
			domainListArr: ['水利', '供水', '排水', '灌溉', '水文', '环保'],
			domainListArrObj: [{
					"text": "水利",
					"value": 0
				},
				{
					"text": "供水",
					"value": 1
				},
				{
					"text": "排水",
					"value": 2
				},
				{
					"text": "灌溉",
					"value": 3
				},
				{
					"text": "水文",
					"value": 4
				},
				{
					"text": "环保",
					"value": 5
				}
			],
			typeListArr: ['设备联网', 'PLC编程', '传感器调试', '设备调试', 'AI算法', '电气电路', '控制系统诊断', '平台开发', '平台运维', '系统对接',
				'数据分析', '机械维修'
			],
			typeListArrObj: [{
				"text": "设备联网",
				"value": 0
			}, {
				"text": "PLC编程",
				"value": 1
			}, {
				"text": "传感器调试",
				"value": 2
			}, {
				"text": "设备调试",
				"value": 3
			}, {
				"text": "AI算法",
				"value": 4
			}, {
				"text": "电气电路",
				"value": 5
			}, {
				"text": "控制系统诊断",
				"value": 6
			}, {
				"text": "平台开发",
				"value": 7
			}, {
				"text": "平台运维",
				"value": 8
			}, {
				"text": "系统对接",
				"value": 9
			}, {
				"text": "数据分析",
				"value": 10
			}, {
				"text": "机械维修",
				"value": 11
			}],
			waysArr: ['远程', '线下'],
			ways: [{
				text: '远程',
				value: 0
			}, {
				text: '线下',
				value: 1
			}],
		};
	},
	onShow() {
		const _userInfo = uni.getStorageSync('_userInfo');
		if (_userInfo) {
			this.userInfo = _userInfo;
			this.handleWindowArea();
			// 监听键盘高度变化
			uni.onKeyboardHeightChange((res) => {
				this.handleOnFocusKeyboardHeight(res);
			});
		}
	},
	onResize() {
		this.handleWindowArea();
	},
	onReady() {
		this.handleWindowArea();
		// 监听键盘高度变化
		uni.onKeyboardHeightChange((res) => {
			this.handleOnFocusKeyboardHeight(res);
		});
	},
	onUnload() {
		uni.offKeyboardHeightChange();
	},
	methods: {
		// 拨打电话
		handlePhoneCall(number) {
			uni.makePhoneCall({
				phoneNumber: number
			});
		},
		// 根据坐标查询地址
		async getLocationByCoordinates(latitude, longitude) {
			const postData = {
				location: `${latitude},${longitude}`
			};
			return await getLocationQQ(postData).then(data => {
				console.log("data --->>>", data)
				if (data.status === 0 && data.result) {
					const address = data.result.formatted_addresses.standard_address;
					console.log('查询到的地址:', data.result);
					this.currentLocationAreaText = address;
					
					return data.result;
				} else {
					console.error('查询失败:', data.info);
				}
			})
		},
		// 将路径参数提取出来并生成对象
		handleUrlParamsToObj(url) {
			// 将参数转化为对象
			const queryString = url.split('?')[1];

			if (!queryString) return false;

			// 将查询字符串转换为键值对对象
			const params = {};
			queryString.split('&').forEach(param => {
				const [key, value] = param.split('=');
				params[key] = decodeURIComponent(value); // 使用 decodeURIComponent 解码
			});

			return params;
		},
		// 跳转到指定页面
		goToPage(pageUrl) {
			//  判断打开的链接是否是 http 如果是 使用 web-view 打开， 反之直接跳转
			if (pageUrl.startsWith("http")) {
				uni.navigateTo({
					url: `/pages/iframe/index?webViewUrl=${encodeURIComponent(pageUrl)}`
				});
			} else {
				// 读取路径参数
				const pageParams = this.handleUrlParamsToObj(pageUrl);
				uni.setStorageSync('demandPageParams', pageParams);
				uni.switchTab({
					url: pageUrl
				});
				uni.navigateTo({
					url: pageUrl
				});
			}
		},
		// 获取键盘高度
		handleOnFocusKeyboardHeight(keyUp) {
			const keyHeight = keyUp.height;
			this.KeyboardHeight = keyHeight;
			const _pageHeightHaveBar = this.pageHeighthaveBar;
			const _pageHeightNoBar = this.pageHeight;
			if (keyHeight > 0) {
				this.pageHaveBarStyle.height = (_pageHeightHaveBar - keyHeight) + 'px';
				this.pageNoHaveBarStyle.height = (_pageHeightNoBar - keyHeight) + 'px';
			} else {
				this.pageHaveBarStyle.height = _pageHeightHaveBar + 'px';
				this.pageNoHaveBarStyle.height = _pageHeightNoBar + 'px';
			}
		},

		// 计算页面高度
		handleWindowArea() {
			const _viewInfo = uni.getWindowInfo().safeArea;
			_viewInfo.statusBarHeight = uni.getWindowInfo().statusBarHeight;
			const _pageHeightNoBar = uni.getWindowInfo().windowHeight - _viewInfo.statusBarHeight;
			const _pageHeightHaveBar = uni.getWindowInfo().windowHeight - _viewInfo.statusBarHeight - 44;
			const _pageTopNohaveBar = _viewInfo.statusBarHeight;
			const _pageTophaveBar = _viewInfo.statusBarHeight + 44;

			this.viewInfo = _viewInfo;
			this.pageHeight = _pageHeightNoBar;
			this.pageHeighthaveBar = _pageHeightHaveBar;

			this.pageHaveBarStyle = {
				top: _pageTophaveBar + 'px',
				height: _pageHeightHaveBar + 'px'
			};
			this.pageNoHaveBarStyle = {
				top: _pageTopNohaveBar + 'px',
				height: _pageHeightNoBar + 'px'
			};
		},
		// 图片放大
		handlePreviewImage(urls) {
			uni.previewImage({
				urls: Array.isArray(urls) ? urls :  [urls]
			})
		},

		// 获取文件信息
		handleGetFileInfo(url) {
			// 提取文件名和扩展名
			const fileName = url.substring(url.lastIndexOf('/') + 1);
			const extname = fileName.split('.').pop(); // 获取扩展名

			// 返回结果
			return {
				url: url,
				extname: extname,
				name: fileName
			};
		},

		// 时间转为时间戳
		handleTimeStampToStr(dateString) {
			let date = new Date(dateString); // 创建 Date 对象
			let timestamp = date.getTime() / 1000; // 获取时间戳（单位是秒）
			return timestamp;
		},

		// 时间格式化
		formatTime(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');

			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		
		// 时间戳格式化
		handleTimeStrToTimeStamp(timeStamp) {
			const _timeStamp = timeStamp,
				now = new Date(),
				date = new Date(_timeStamp * 1000),
				// 格式化时分秒
				hours = String(date.getHours()).padStart(2, '0'),
				minutes = String(date.getMinutes()).padStart(2, '0'),
				seconds = String(date.getSeconds()).padStart(2, '0');

			const diffTime = now - date;
			const diffDays = Math.abs(Math.floor(diffTime / (1000 * 60 * 60 * 24))); // 计算天数差
			
			// 判断时间差
			if (diffDays === 1) {
				return `昨天 ${hours}:${minutes}:${seconds}`;
			} else if (diffDays === 2) {
				return `前天 ${hours}:${minutes}:${seconds}`;
			} else if (diffDays > 2) {
				// 返回年月日和时分秒
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1并补充零
				const day = String(date.getDate()).padStart(2, '0'); // 补充零以保持两位数字

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}

			// 如果是今天，返回具体时间
			return `今天 ${hours}:${minutes}:${seconds}`
		},

		//  订单列表的时间计算
		handleTimeDifference(timestamp1, timestamp2) {
			// 计算时间差（秒）
			let differenceInSeconds = Math.abs(timestamp2 - timestamp1);

			// 计算天数、小时数、分钟数、秒数
			let days = Math.floor(differenceInSeconds / (24 * 3600));
			differenceInSeconds %= (24 * 3600);
			let hours = Math.floor(differenceInSeconds / 3600);
			differenceInSeconds %= 3600;
			let minutes = Math.floor(differenceInSeconds / 60);
			let seconds = differenceInSeconds % 60;

			// 返回格式化后的字符串
			return `${days}天${hours}小时${minutes}分钟后投稿截止`;
		}

	}
};